import {defineStore} from "pinia";
import {ApiLanguage} from "@/api/common/index.js";
import cache from "@/plugins/cache.js";
import cart from './cart'
import i18n from '@/locale'
import useCartStore from '@/store/modules/cart'

const useLangStore = defineStore(
  'lang',
  {
    state: () => ({
      language: cache.local.get('Coupon-Lang') || 'zh',
      languageList: []
    }),
    getters: {
      languageId() {
        return this.languageList.find(item => item.langKey === this.language)?.id
      },
      languageName() {
        return this.languageList.find(item => item.langKey === this.language)?.countryName
      },
      languageIcon() {
        return this.languageList.find(item => item.langKey === this.language)?.icon
      },
      languageRate() {
        return this.languageList.find(item => item.langKey === this.language)?.rate || 1
      },
      languageSymbol() {
        return this.languageList.find(item => item.langKey === this.language)?.symbol || '¥'
      },
    },
    actions: {
      async getLanguageList() {
        return ApiLanguage().then(res => {
          this.languageList = res.data
        })
      },
      async setLanguage(lang) {
        return new Promise(async (resolve, reject) => {
          try {
            this.language = lang;
            const { locale } = i18n.global
            locale.value = lang
            cache.local.set('Coupon-Lang', lang)
            resolve()
          } catch (err) {
            reject()
          }
        })
      }
    }
  })

export default useLangStore
